/**
 * 给文件追加内容
 * 
 * 父进程将文件偏移指针到文件尾
 * 子进程往文件中写入内容
 * 
 * 传入的文件需存在，且已有内容
 * 
 * 
 * gcc -g -rdynamic -I include    -O0 -Wall  -o obj/progress_file_append src/progress_file_append.c
 * obj/progress_file_append s.txt
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    if (argc < 2)
    {
        fprintf(stderr, "Usage: \n\t%s <filename>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int fd = open(argv[1], O_WRONLY);
    if (2 > fd)
    {
        perror("open error: ");
        exit(EXIT_FAILURE);
    }

    pid_t pid = fork();
    if (0 == pid)
    {
        // 子进程
        char *str = "Hello Gino\n";
        printf("I am child progress id is %d\n", getpid());
        sleep(3);
        write(fd, str, strlen(str));
    }
    else if (0 < pid)
    {
        // 父进程
        printf("I am parent progress id is %d\n", getpid());
        lseek(fd, 0, SEEK_END);
    }
    else
    {
        perror("fork error : ");
        exit(EXIT_FAILURE);
    }

    close(fd);
    return 0;
}